package com.mtw.bbs.bbsUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.mtw.bbs.bbsUser.mapper.UserRoleMapper;
import com.mtw.bbs.bbsUser.pojo.entity.UserRole;
import com.mtw.bbs.bbsUser.service.UserRoleService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色逻辑层
 * @author mo
 * @email mo
 * @date 2023-10-18 15:44:13
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    /**
     * 给用户添加角色
     */
    @Override
    @Transactional
    public boolean saveBatch(String userId, Collection<String> roleIds) {
        if (CollectionUtils.isEmpty(roleIds))
            return false;
        removeByUserId(userId);
        Set<UserRole> userRoles = roleIds.stream().map(roleId -> new UserRole(userId, roleId)).collect(Collectors.toSet());
        return saveBatch(userRoles);
    }


    /**
     * 删除用户拥有的角色
     */
    @Override
    @Transactional
    public boolean removeByUserId(String userId) {
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId, userId);
        return remove(lqw);
    }


    /**
     * 删除用户拥有的角色
     */
    @Override
    @Transactional
    public boolean removeByRoleIds(Collection<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.in(UserRole::getRoleId, ids);
        return remove(lqw);
    }


    /**
     * 根据userId查询用户拥有角色id集合
     */
    @Override
    public Set<String> queryByUserId(String userId) {

        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId, userId);
        List<UserRole> userRoleList = list(lqw);
        return userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
    }



}
